package com.jacen.etl.dao;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import com.jacen.etl.entity.EtlScriptEntity;
import com.jacen.etl.util.HttpParamCaster;
import com.jacen.etl.util.SqlCondition;

public class EtlScriptDao extends BaseDao<EtlScriptEntity>{

	/**
	 * 分页查询所有实体
	 */
	
	@SuppressWarnings("unchecked")
	public List<EtlScriptEntity> getPage(Session session, int page, int size, Map<String, Object> mapParams) {
		String sql = "from EtlScriptEntity t where %s";
		SqlCondition cond = getPageCondition(mapParams);
		sql = String.format(sql, cond.getCondition());
		Query query = session.createQuery(sql);
		setQueryCondition(query, cond.getParams());
		query.setFirstResult((page - 1) * size).setMaxResults(size);
		return (List<EtlScriptEntity>)query.list();
	}
	/**
	 * 根据条件查询实体总数
	 */
	public long getCount(Session session, Map<String, Object> mapParams){
		String sql = "select count(*) from EtlScriptEntity t where  %s";
		SqlCondition cond = getPageCondition(mapParams);
		sql = String.format(sql, cond.getCondition());
		Query query = session.createQuery(sql);
		setQueryCondition(query, cond.getParams());
		return ((BigDecimal) query.uniqueResult()).longValue();
	}
	
	/**
	 * 判断实体是否存在（修改）
	 * @param Session
	 * @param propertyName
	 * @param propertyValue
	 * @param id
	 */
	public boolean existEntityFU(Session session,String propertyName, Object propertyValue, String id) {
		String hql = "select count(*) from " + entityClass.getName()
				+ " where 1 = 1 %s";
		hql = String.format(hql, "and " + propertyName + "= ? and id != ?");
		return getCount(session,hql, propertyValue, id) > 0;
	}
	
	private SqlCondition getPageCondition(Map<String, Object> mapParams) {
		SqlCondition cond = new SqlCondition();
		if(HttpParamCaster.paramIsNotEmpty(mapParams.get("entityId"))) cond.equal("t.entityId", mapParams.get("entityId"));
		return cond;
	}
	
	
	private void setQueryCondition(Query query, List<Object> list) {
		for (int i = 0; i < list.size(); i++) {
			Object obj = list.get(i);
			query.setParameter(i, obj);
		}
	}	
}


